package cpe.hapa.dao;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

import cpe.hapa.model.Vol;

public class VolDAO {

	public static Key addVol(Vol vol)
	{
		DatastoreService datastore = DatastoreSingleton.getInstance();
		
		try {
			vol.getDepartureDate().setTime(vol.getDepartureDate().getTime() + new SimpleDateFormat("HH:mm").parse(vol.getDepartureTime()).getTime());
			vol.getArrivalDate().setTime(vol.getArrivalDate().getTime() + new SimpleDateFormat("HH:mm").parse(vol.getArrivalTime()).getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		};
		
		
		Entity newVol = new Entity("Vol");
		newVol.setProperty("leavingFrom", vol.getLeavingFrom());
		newVol.setProperty("goingTo", vol.getGoingTo());
		newVol.setProperty("departure", vol.getDepartureDate());
		newVol.setProperty("arrival", vol.getArrivalDate());
		newVol.setProperty("departureDate", new SimpleDateFormat("yyyy-MM-dd").format(vol.getDepartureDate()));
		newVol.setProperty("arrivalDate", new SimpleDateFormat("yyyy-MM-dd").format(vol.getArrivalDate()));
		newVol.setProperty("departureTime", vol.getDepartureTime());
		newVol.setProperty("arrivalTime", vol.getArrivalTime());
		newVol.setProperty("duration", vol.getDuration());
		newVol.setProperty("price", vol.getPrice());
		newVol.setProperty("availableSeats", vol.getAvailableSeats());
		
		return datastore.put(newVol);
	}

	public static PreparedQuery getSearchVol(String leavingFrom,String goingTo, Date departure) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		FilterPredicate leavingFromFilter = new FilterPredicate("leavingFrom", Query.FilterOperator.EQUAL, leavingFrom);
		FilterPredicate goingToFilter = new FilterPredicate("goingTo", Query.FilterOperator.EQUAL, goingTo);
		FilterPredicate dateFilter = new FilterPredicate("departure", Query.FilterOperator.GREATER_THAN_OR_EQUAL, departure);
		Filter filter = CompositeFilterOperator.and(leavingFromFilter, goingToFilter, dateFilter); 
		
		Query volListQuery = new Query("Vol").setFilter(filter)
		.addSort("departure", SortDirection.ASCENDING);
		
		return datastore.prepare(volListQuery);
	}
}
